﻿using Example1.Domain.AggregatesModel.ExampleAggregate;
using Example1.Infrastructure.Repositories;

using Microsoft.AspNetCore.Authorization;

using Tszy.API.Test1;
using Tszy.Unlimited.AspNetCore;
using Tszy.Unlimited.AspNetCore.Filters;
using Tszy.Unlimited.Data.FreeSQL;

namespace Tszy.API;

public static class Startup
{
    public static void Configure(this WebApplicationBuilder builder)
    {
        builder.RegisterTszyComponent().RegisterSwagger("普通用户 API 文档").RegisterCors();
        builder.Services.RegisterAuthentication();
        builder.Services.AddTransient<Test11>();
        builder.Services.AddTransient<Test11>();
        builder.Services.RegisterFreeSQLDotMySQL("server=localhost;port=3306;uid=root;pwd=111111;database=pay;charset=utf8;SslMode=None");
        builder.Services.AddTransient<IExampleUserRepository, ExampleUserRepository>();
    }

    public static void UseApp(this WebApplication app)
    {
        app.UseTszyComponent().UseSwagger().UseCors();
        app.UseMiddleware<RequestCoreFilter>();

        //注意！以下2个中间件的使用，顺序不能错，否则无法正常使用授权验证。
        app.UseAuthentication();
        app.UseAuthorization();
    }

    private static void RegisterAuthentication(this IServiceCollection services, string identityServerUrl = "")
    {
        services.AddSingleton<IAuthorizationHandler, AppAuthorizationHandler>();
        services.AddAuthorization(optins =>
        {
            //增加授权策略检测
            //用户中心
            optins.AddPolicy("UserPolicy", polic =>
            {
                polic.AddRequirements(new AppAuthorizationRequirement("User"));
            });
            //管理员用户
            optins.AddPolicy("AdminPolicy", polic =>
            {
                polic.AddRequirements(new AppAuthorizationRequirement("Admin"));
            });
            //系统之间调用权限验证
            optins.AddPolicy("SystemPolicy", polic =>
            {
                polic.AddRequirements(new AppAuthorizationRequirement("System"));
            });
            //匿名用户
            optins.AddPolicy("AnonymousPolicy", polic =>
            {
                polic.AddRequirements(new AppAuthorizationRequirement("Anonymous"));
            });
            //匿名用户
            optins.AddPolicy("MerchantPolicy", polic =>
            {
                polic.AddRequirements(new AppAuthorizationRequirement("Merchant"));
            });
        });
    }
}

public class AppAuthorizationRequirement : IAuthorizationRequirement
{
    /// <summary>
    /// 
    /// </summary>
    public AppAuthorizationRequirement(string policyname, int code = -1, string message = "")
    {
        this.Name = policyname;
        Code = code;
        Message = message;
        Data = false;
    }

    public string Name { get; set; }
    public int Code { get; set; }
    public string Message { get; set; }
    public object Data { get; set; }

}

public class AppAuthorizationHandler : AuthorizationHandler<AppAuthorizationRequirement>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AppAuthorizationRequirement requirement)
    {
        var roleName = requirement.Name;

        if (roleName == "System")
        {
            context.Succeed(requirement);
        }
        else
        {
            requirement.Message = "没有权限！";
            requirement.Code = 50008;
            context.Fail();
        }

        await Task.CompletedTask;
    }
}